package com.jinxinol.basic.system.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.jinxinol.basic.system.domain.SysAttachment;
import com.jinxinol.basic.system.domain.SysConfig;
import com.jinxinol.basic.system.service.ISysAttachmentService;
import com.jinxinol.basic.system.service.ISysConfigService;
import com.jinxinol.core.common.BaseAction;
/**
 * 
 * @company Jinxin Computer Corp.
 * @author LXD
 * @email 247428412@qq.com
 * @description 附件处理
 * @date 2012-09-05
 */
public class UpFileAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	private File[] upload;// 实际上传文件
	private String[] uploadContentType; // 文件的内容类型
	private String[] uploadFileName; // 上传文件名
	String filestr = "";
	private String filetype;// 附件类型
	
	private SysAttachment sysfile;
	
	@Resource ISysConfigService sysConfigService;
	@Resource ISysAttachmentService sysAttachmentService;

	/**
	 * 文件上传处理
	 * */
	public void upload() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();
		SimpleDateFormat FormattedFileName = null;
		FormattedFileName = new SimpleDateFormat("yyyyMMddHHmmssSSSS");
		try {
			SysConfig config=new SysConfig();
			config.setKey("sys_file_path");//系统配置目录
			String path = sysConfigService.find(config).get(0).getValue();
			path = getKindPath(path,filetype);
			filestr += "<table wight=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"5\">";
			for (int i = 0; i < upload.length; i++) {
				
				Date d = new java.util.Date();
				String realName = FormattedFileName.format(d).toString() + i + (int)(new Random().nextDouble()*100) + getExt(uploadFileName[i]);
				
				String old_name = uploadFileName[i];  //附件名称(原)
				String new_name = realName;  //附件名称(新)
				String file_path = path + realName;  //存放路径
				String att_type = filetype;  //业务类型：（例：MAIL-邮件）
				String file_type = uploadContentType[i];  //文件类型
				Long file_size = upload[i].length();  //文件大小
				Integer up_user = sysUser.getId();  //上传人
				
//				SysAttachment t=new SysAttachment();
//				
//				t.setBus_id(1);
//				t.setOld_name(old_name);
//				t.setNew_name(new_name);
//				t.setFile_path(file_path);
//				t.setAtt_type(att_type);
//				t.setFile_type(file_type);
//				t.setFile_size(file_size);
//				t.setUp_user(up_user);
//				
//				sysAttachmentService.insert(t);
				
				File target = new File(path, realName);
				FileUtils.copyFile(upload[i], target);// 上传至服务器的目录
				//反斜线 替换
				file_path=file_path.replace(File.separator, File.separator+File.separator);
				filestr += "<tr><td class=\"tdstyle_17\"><input type=\"hidden\" name=\"filelist["+i+"].file_path\" value=\"" + file_path + "\" />"
				 		+ "<input type=\"hidden\" name=\"filelist["+i+"].old_name\" value=\"" + old_name + "\" />"
				 		+ "<input type=\"hidden\" name=\"filelist["+i+"].new_name\" value=\"" + new_name + "\" />"
				 		+ "<input type=\"hidden\" name=\"filelist["+i+"].att_type\" value=\"" + att_type + "\" />"
				 		+ "<input type=\"hidden\" name=\"filelist["+i+"].file_type\" value=\"" + file_type + "\" />"
				 		+ "<input type=\"hidden\" name=\"filelist["+i+"].file_size\" value=\"" + file_size + "\" />"
				 		+ "<input type=\"hidden\" name=\"filelist["+i+"].up_user\" value=\"" + up_user + "\" />"
						+ old_name
						+ "</td><td class=\"tdstyle_17\"> <a href=\"javascript:void(0)\" onclick=\"deltr(this)\">删除</a></td></tr>";
			}
			filestr += "</table>";
			out.println("<script> parent.filestr = '" + filestr
					+ "'; parent.chuli(); </script>"); // 输出调用父页面js
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			throw new  Exception("附件上传错误！\n详细日志："+e.getMessage());
		}
	}
	
	/**
	 * 下载文件方法 参数 附件表ID
	 */
	public void fileDown() throws Exception {
		sysfile = sysAttachmentService.findById(sysfile.getAtt_id());
		response.setCharacterEncoding("utf-8");
		response.addHeader("Content-Disposition", "attachment;filename="
				+ URLEncoder.encode(sysfile.getOld_name(), "utf-8"));// 对name编了码，因为汉字在文件头里不能用
		InputStream in = null; // 读入
		OutputStream out = null; // 输出
		File file = new File(sysfile.getFile_path());
		if (!file.exists())
			return;
		in = new FileInputStream(sysfile.getFile_path()); // 服务器的绝对路径建立输入流
		out = response.getOutputStream(); // 建立输出流
		byte buf[] = new byte[1024];
		int len = 0;
		try {
			while (true) {
				// 读取文件内容
				len = in.read(buf, 0, 1024);
				if (len <= 0)
					break;
				// 将读到的结果写给客户端
				out.write(buf, 0, len);
			}
			in.close(); // 关闭输入流
			out.flush(); // 刷新缓存
			out.close(); // 关闭输出流
		} catch (IOException ioe) {
			// 客户端停止下载或关闭浏览器会出现异常，此处不处理
			// System.out.println("客户端强制关闭"+out);
			throw new  Exception("附件下载错误！\n详细日志："+ioe.getMessage());
		}
	}
	
	/**
	 * 提交表单附件 例子
	 * */
	public void add(){
		sysAttachmentService.insert(filelist, 2);
	}
	
	
	/**
	 * 文件上传存储目录
	 * Parameter:path1 系统文件配置目录
	 * Parameter:TYPE 类别
	 *  例：notice代表公告，mail代表邮件 等
	 *  window  返回一个路径：path1/TYPE(?)/2012/09/05/
	 *  linux  path1/TYPE/YYYY/MM//DD/
	 */
	 public String getKindPath(String path1, String type) {
//		String os=System.getProperty("os.name").toLowerCase();
//		if(os.startsWith("windows")){   
//            //本地是windows   
//			path1 = path1.substring(0, path1.indexOf(File.separator) + 1);// 取得根目录，例如D:/  
//        }else{   
//            //本地是非windows系统 一般就是unix   
//        	path1=File.separator+"home"+File.separator; 
//        }   
		String t1 = new java.sql.Timestamp(System.currentTimeMillis())
				.toString().substring(0, 4);// 年*/
		String t2 = new java.sql.Timestamp(System.currentTimeMillis())
				.toString().substring(5, 7);// 月*/
		String t3 = new java.sql.Timestamp(System.currentTimeMillis())
				.toString().substring(8, 10);// 日*/
		// 返回一个路径：path1/TYPE(?)/2010/09/28/*/
		String path = "";;
		if (path1.substring(path1.length()-1,path1.length()).equals(File.separator)) {
			path = path1 + type
			+ File.separator + t1 + File.separator + t2 + File.separator
			+ t3 + File.separator;
		}else {
			path = path1 + File.separator + type
			+ File.separator + t1 + File.separator + t2 + File.separator
			+ t3 + File.separator;
		}
		
		// 判断路径是否已存在，如果不存在，则生成这个路径
		File f = new File(path);
		if (!f.exists()) {
			f.mkdirs();
		}
		return path;
	}

	public String getFiletype() {
		return filetype;
	}

	public void setFiletype(String filetype) {
		this.filetype = filetype;
	}

	public File[] getUpload() {
		return upload;
	}

	public void setUpload(File[] upload) {
		this.upload = upload;
	}

	public String[] getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String[] uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String[] getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String[] uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public static String getExt(String fileName) {
		return fileName.substring(fileName.lastIndexOf("."));
	}

	public SysAttachment getSysfile() {
		return sysfile;
	}

	public void setSysfile(SysAttachment sysfile) {
		this.sysfile = sysfile;
	}

}
